package com.xbongbong.paas.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.ext.FieldPermissionEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasProcessTemplateEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasProcessTemplateNodeEntityExt;
import com.xbongbong.paas.model.PaasProcessTemplateModel;
import com.xbongbong.paas.model.PaasProcessTemplateNodeModel;
import com.xbongbong.paas.pojo.dto.ScriptFlowFormDTO;
import com.xbongbong.paas.pojo.vo.ScriptFlowFormVO;
import com.xbongbong.paas.service.FlowFormExplainsService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.CommentUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.StatisticsServicesErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.TemplateErrorCodeEnum;
import com.xbongbong.saas.constant.ErrorMessageConstant;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ContractEnum;
import com.xbongbong.saas.enums.business.PurchaseEnum;
import com.xbongbong.saas.enums.business.SupplierEnum;
import com.xbongbong.saas.script.modifyenum.ScriptContractFlowExplainsEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 应用模块名称<p>
 * 代码描述<p>
 * Company: 逍邦网络科技有限公司<p>
 *
 * @author chenshan
 * @version v1.0
 * @since 2019-12-12 14:09
 */
@Service("flowFormExplains")
public class FlowFormExplainsServiceImpl implements FlowFormExplainsService {
    private static final Logger LOGGER = LoggerFactory.getLogger(FlowFormExplainsServiceImpl.class);
    @Resource
    private PaasProcessTemplateModel paasProcessTemplateModel;
    @Resource
    private PaasProcessTemplateNodeModel paasProcessTemplateNodeModel;
    @Override
    public ScriptFlowFormVO repairFlowExplain(ScriptFlowFormDTO scriptFlowFormDTO) throws XbbException {
        ScriptFlowFormVO scriptFlowFormVO = new ScriptFlowFormVO();
        Long startTime = DateTimeUtil.getInt();
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(scriptFlowFormDTO.getBusinessType());
        if ( Objects.equals(xbbRefTypeEnum, XbbRefTypeEnum.UNKNOWN.getCode() )){
            throw new XbbException(TemplateErrorCodeEnum.API_ERROR_350006);
        }
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("businessType", xbbRefTypeEnum.getCode());
        param.put("del", 0);
        List<String> corpidList = scriptFlowFormDTO.getCorpidList();
        CommentUtil.addToMap(param,"corpidList", corpidList);
        List<PaasProcessTemplateEntityExt> paasProcessTemplateEntityExtList = paasProcessTemplateModel.list(param);
        if ( CollectionsUtil.isEmpty(paasProcessTemplateEntityExtList) ){
            throw new XbbException(StatisticsServicesErrorCodeEnum.API_ERROR_224024.getCode(), ErrorMessageConstant.SCRIPT_PROCESS_ERROR_MSG,xbbRefTypeEnum.getName(),0);
        }
        List<Long> processTemplateId = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        paasProcessTemplateEntityExtList.forEach(item ->{
            processTemplateId.add(item.getId());
        });
        param.clear();
        param.put("templateIdIn", processTemplateId);
        param.put("del", 0);
        List<PaasProcessTemplateNodeEntityExt> paasProcessTemplateNodeEntityExtList = paasProcessTemplateNodeModel.list(param);
        if ( CollectionsUtil.isEmpty(paasProcessTemplateNodeEntityExtList) ){
            throw new XbbException(StatisticsServicesErrorCodeEnum.API_ERROR_224024.getCode(), ErrorMessageConstant.SCRIPT_PROCESS_ERROR_MSG,xbbRefTypeEnum.getName(),0);
        }
        List<FieldPermissionEntityExt> fieldList = new ArrayList<>(2);
        List<FieldPermissionEntityExt> delFieldList = new ArrayList<>(2);
        ScriptContractFlowExplainsEnum.getAllEnum().forEach(item ->{
            FieldPermissionEntityExt fieldPermissionEntityExt = new FieldPermissionEntityExt();
            BeanUtil.copyProperties(item, fieldPermissionEntityExt);
            fieldList.add(fieldPermissionEntityExt);
        });
//        for ( PaasProcessTemplateNodeEntityExt item : paasProcessTemplateNodeEntityExtList ) {
//            List<FieldPermissionEntityExt> fieldPermissionList= JSONArray.parseArray(item.getFieldPermission(), FieldPermissionEntityExt.class);
//            for ( FieldPermissionEntityExt fieldPermissionEntityExt : fieldPermissionList ) {
//                if ( Objects.equals(fieldPermissionEntityExt.getAttr(), ContractEnum.ADD_WRITE_OFF_PREPAYMENT.getAttr())
//                        || Objects.equals(fieldPermissionEntityExt.getAttr(), ContractEnum.ADD_PAYMENT_SHEET.getAttr())){
//                    delFieldList.add(fieldPermissionEntityExt);
//                }
//            }
//            if ( Objects.equals(scriptFlowFormDTO.getOperateFlag(),1) ){
//                fieldPermissionList.addAll(fieldList);
//            } else if ( Objects.equals(scriptFlowFormDTO.getOperateFlag(),2) ){
//                fieldPermissionList.removeAll(delFieldList);
//                fieldPermissionList.removeAll(fieldList);
//            }
//            item.setFieldPermission(JSONObject.toJSONString(fieldPermissionList));
//        }
        paasProcessTemplateNodeEntityExtList.forEach(item ->{
            List<FieldPermissionEntityExt> fieldPermissionList= JSONArray.parseArray(item.getFieldPermission(), FieldPermissionEntityExt.class);
            switch (xbbRefTypeEnum) {
                case SUPPLIER:
                    for ( FieldPermissionEntityExt fieldPermissionEntityExt : fieldPermissionList ) {
                        if ( Objects.equals(fieldPermissionEntityExt.getAttr(), SupplierEnum.ADD_SUPPLIER_CONTACT.getAttr())){
                            delFieldList.add(fieldPermissionEntityExt);
                        }
                    }
                    break;
                case PURCHASE:
                    for ( FieldPermissionEntityExt fieldPermissionEntityExt : fieldPermissionList ) {
                        if ( Objects.equals(fieldPermissionEntityExt.getAttr(), PurchaseEnum.ADD_WRITE_OFF_PREPAY.getAttr())
                                || Objects.equals(fieldPermissionEntityExt.getAttr(), PurchaseEnum.ADD_PAY_SHEET.getAttr())){
                            delFieldList.add(fieldPermissionEntityExt);
                        }
                    }
                    break;
                case CONTRACT:
                    for ( FieldPermissionEntityExt fieldPermissionEntityExt : fieldPermissionList ) {
                        if ( Objects.equals(fieldPermissionEntityExt.getAttr(), ContractEnum.ADD_WRITE_OFF_PREPAYMENT.getAttr())
                                || Objects.equals(fieldPermissionEntityExt.getAttr(), ContractEnum.ADD_PAYMENT_SHEET.getAttr())){
                            delFieldList.add(fieldPermissionEntityExt);
                        }
                    }
                    break;
                default:
                    break;
            }
            if ( Objects.equals(scriptFlowFormDTO.getOperate(),0) ){
                fieldPermissionList.addAll(fieldList);
            } else if ( Objects.equals(scriptFlowFormDTO.getOperate(),1) ){
                fieldPermissionList.removeAll(delFieldList);
                fieldPermissionList.removeAll(fieldList);
            }
            item.setFieldPermission(JSONObject.toJSONString(fieldPermissionList));
        });
        Integer count = paasProcessTemplateNodeModel.updateBatchById(paasProcessTemplateNodeEntityExtList);
        scriptFlowFormVO.setMsg(String.format(I18nMessageUtil.getMessage(ErrorMessageConstant.SCRIPT_PROCESS_ERROR_MSG),xbbRefTypeEnum.getName(),count));
        LOGGER.info("---更新合同、采购合同、供应商流程表单解释脚本结束");
        Long endTime = DateTimeUtil.getInt();
        Long consumeTime = endTime - startTime;
        LOGGER.info("---耗时为："+ consumeTime);
        return scriptFlowFormVO;
    }
}
